﻿var tagManagerServiceUrl = '';

$(function () {
	$.blockUI.defaults.css = {};
	$.blockUI.defaults.fadeIn = 0;
	$.blockUI.defaults.fadeOut = 0;

	function bindContextMenu() {
		$(".dynatree-node").not(".dynatree-folder")
		.destroyContextMenu()
		.contextMenu({ menu: "tagContextMenu" }, function (action, el, pos) {
			var node = el.parents("[dtnode]").prop("dtnode");
			var parentNode = el.parent().parents("[dtnode]").prop("dtnode");
			switch (action) {
				case "edit":
					var editFormLocation = $('#hdnEditTagForm').val();
					if (editFormLocation.indexOf('openFormDialog') > -1) {
						eval(editFormLocation.replace("')", '?ID=' + node.data.key.split('|')[0] + "')"));
					} else {
						window.location = editFormLocation + '?ID=' + node.data.key.split('|')[0] + '&Source=' + encodeURIComponent(window.location);
					}
					break;
				case "addNew":
					var newFormLocation = $('#hdnNewTagForm').val();
					if (newFormLocation.indexOf('openFormDialog') > -1) {
						eval(newFormLocation.replace("')", '?category=' + node.data.key.split('|')[3] + '&parent=' + node.data.key.split('|')[1] + '&tree=' + $('#tagTreeId').text() + "')"));
					} else {
						window.location = newFormLocation + '?category=' + node.data.key.split('|')[3] + '&parent=' + node.data.key.split('|')[1] + '&tree=' + $('#tagTreeId').text() + '&Source=' + encodeURIComponent(window.location);
					}
					break;
				case "addExisting":
					$('#hdnParentKey').val(node.data.key);
					if (node.hasChildren()) {
						$('#hdnSiblingKey').val(node.getChildren()[0].data.key);
					} else {
						$('#hdnSiblingKey').val(node.data.key);
					}

					$.blockUI({ message: $('#tagSelectionModal') });
					break;
				case "remove":
					node.removeChildren();
					node.remove();
					$.ajax({
						url: tagManagerServiceUrl + "/RemoveTagHierarchyPosition",
						data: { 'key': node.data.key },
						dataType: 'json',
						contentType: "application/json; charset=utf-8",
						processdata: true
					});
					break;
				case "delete":
					if (confirm('Are you sure you would like to delete the ' + node.data.title + ' Tag?')) {
						$.ajax({
							url: tagManagerServiceUrl + "/DeleteTag",
							data: { 'key': node.data.key },
							dataType: 'json',
							contentType: "application/json; charset=utf-8",
							processdata: true,
							success: function () { location.reload(true); }
						});
					}
					break;
			};
		});

		$(".dynatree-folder")
		.destroyContextMenu()
		.contextMenu({ menu: "tagCategoryContextMenu" }, function (action, el, pos) {
			var node = el.parents("[dtnode]").prop("dtnode");
			switch (action) {
				case "edit":
					var editFormLocation = $('#hdnEditTagCategoryForm').val();
					if (editFormLocation.indexOf('openFormDialog') > -1) {
						eval(editFormLocation.replace("')", '?ID=' + node.data.key.split('|')[0] + "')"));
					} else {
						window.location = editFormLocation + '?ID=' + node.data.key.split('|')[0] + '&Source=' + encodeURIComponent(window.location);
					}
					break;
				case "addNew":
					var newFormLocation = $('#hdnNewTagForm').val();
					if (newFormLocation.indexOf('openFormDialog') > -1) {
						eval(newFormLocation.replace("')", '?category=' + node.data.key.split('|')[1] + '&tree=' + $('#tagTreeId').text() + "')"));
					} else {
						window.location = newFormLocation + '?category=' + node.data.key.split('|')[1] + '&tree=' + $('#tagTreeId').text() + '&Source=' + encodeURIComponent(window.location);
					}
					break;
				case "addExisting":
					$('#hdnParentKey').val(node.data.key);
					if (node.hasChildren()) {
						$('#hdnSiblingKey').val(node.getChildren()[0].data.key);
					} else {
						$('#hdnSiblingKey').val(node.data.key);
					}
					$.blockUI({ message: $('#tagSelectionModal') });
					break;
				case "remove":
					node.removeChildren();
					node.remove();
					$.ajax({
						url: tagManagerServiceUrl + "/RemoveTagHierarchyPosition",
						data: { 'key': node.data.key },
						dataType: 'json',
						contentType: "application/json; charset=utf-8",
						processdata: true
					});
					break;
				case "delete":
					if (confirm('Are you sure you would like to delete the ' + node.data.title + ' Tag Category?')) {
						$.ajax({
							url: tagManagerServiceUrl + "/DeleteTagCategory",
							data: { 'key': node.data.key },
							dataType: 'json',
							contentType: "application/json; charset=utf-8",
							processdata: true,
							success: function () { location.reload(true); }
						});
					}
					break;
			};
		});
	};

	$("#tree").dynatree({
		initAjax: {
			url: tagManagerServiceUrl + "/GetTagTree",
			data: { 'tagTreeId': $('#tagTreeId').text() }
		},
		onPostInit: function (isReloading, isError) {
			bindContextMenu();
		},
		onExpand: function (isExpanded, node) {
			bindContextMenu();
		},
		dnd: {
			preventVoidMoves: true,
			onDragStart: function (node) { return true; },
			onDragEnter: function (node, sourceNode) {
				//Can only move non-folder node "over" folder node
				if (!sourceNode.data.isFolder && node.data.isFolder) {
					return ["over"];
				}

				//Cannot move node if: 
				//the target is one of the moving node's descendents, 
				//the target is not the same type as the moving node,
				//the moving node is a folder and target is not another folder
				//at the same level
				if (node.isDescendantOf(sourceNode) ||
					sourceNode.data.isFolder != node.data.isFolder ||
					(sourceNode.data.isFolder && node.parent !== sourceNode.parent)) {
					return false;
				}

				//If moving node is folder, cannot move "over"
				if (sourceNode.data.isFolder) {
					return ["before", "after"];
				} else {
					return ["before", "after", "over"];
				}
			},
			onDrop: function (node, sourceNode, hitMode, ui, draggable) {

				sourceNode.move(node, hitMode);

				if (sourceNode.data.isFolder) {
					reorderTagCategories();
				} else {
					reorderTags();
					$.ajax({
						url: tagManagerServiceUrl + "/MoveTagHierarchyPosition",
						dataType: 'json',
						contentType: "application/json; charset=utf-8",
						processdata: true,
						data: { 'key': sourceNode.data.key, 'target': node.data.key, 'mode': hitMode, 'tagTreeId': $('#tagTreeId').text() }
					});
				}
			}
		}
	});

	$('#lnkCloseModal').click(function () {
		$.unblockUI({ onUnblock:
					function () {
						if ($('#txtTagLookup').val() != '') {
							$('#txtTagLookup').val('');
						}
					}
		});
	});

	$('#btnAddTag').click(function () {
		$.unblockUI({ onUnblock:
					function () {
						if ($('#txtTagLookup').val() != '') {
							$.ajax({
								url: tagManagerServiceUrl + "/GetNewTreeNodeForExistingTag",
								dataType: 'json',
								contentType: "application/json; charset=utf-8",
								processdata: true,
								data: { 'parentKey': $('#hdnParentKey').val(), 'tagName': $('#txtTagLookup').val(), 'tagTreeId': $('#tagTreeId').text() },
								success: addTagToTree
							});
							$('#txtTagLookup').val('');
						}
					}
		});
	});

	$('#btnAddNewCategory').click(function () {
		var newFormLocation = $('#hdnNewCategoryForm').val();
		if (newFormLocation.indexOf('openFormDialog') > -1) {
			eval(newFormLocation);
		} else {
			window.location = newFormLocation + '?Source=' + encodeURIComponent(window.location);
		}
	});

	$("#txtTagLookup").autocomplete({
		source: function (request, response) {
			$.ajax({
				url: tagManagerServiceUrl + "/GetExistingTagNames",
				data: { 'searchTerm': request.term },
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				processdata: true,
				dataFilter: function (data) { return data; },
				success: function (data) {
					response($.map(data, function (item) {
						return {
							label: item.value,
							value: item.value
						}
					}))
				}
			});
		},
		json: true,
		shownoresults: true,
		maxresults: 25
	});

	$(":text").each(function () {
		var ctrlLookup = document.getElementById('txtTagLookup');
		if (ctrlLookup == this) {
			if (this.value != "") {
				this.defaultText = this.value;
				$(this)
						  .focus(function () { if (this.value == this.defaultText) { this.value = ""; $(this).addClass("normal-font"); } })
						  .blur(function () { if (this.value == "" && this.defaultText) { this.value = this.defaultText; $(this).removeClass("normal-font"); } });
			}
		}
	});

	function addTagToTree(node) {
		if (node.key != '') {
			var parentNode = $("#tree").dynatree("getTree").getNodeByKey($('#hdnParentKey').val());
			var siblingNode = $("#tree").dynatree("getTree").getNodeByKey($('#hdnSiblingKey').val());

			if (parentNode.data.key == siblingNode.data.key) {
				parentNode.addChild({ title: node.title, key: node.key });
			} else {
				parentNode.addChild({ title: node.title, key: node.key }, siblingNode);
			}
			reorderTags();
			bindContextMenu();
		}
	}

	function reorderTagCategories() {
		var tree = $("#tree").dynatree("getTree");
		var orderedNodes = new Array();
		var i = 0;

		tree.visit(function (node) {
			if (node.data.isFolder) {
				orderedNodes[i] = node.data.key;
				i++;
			}
		});

		$.ajax({
			url: tagManagerServiceUrl + "/ReorderTagCategories",
			data: '{ "orderedTagCategoryKeys" : "' + orderedNodes.join(',') + '" }',
			dataType: 'json',
			type: 'POST',
			contentType: "application/json; charset=utf-8",
			processdata: true
		});
	}

	function reorderTags() {
		var tree = $("#tree").dynatree("getTree");
		var orderedNodes = new Array();
		var i = 0;

		tree.visit(function (node) {
			if (!node.data.isFolder) {
				orderedNodes[i] = node.data.key;
				i++;
			}
		});

		$.ajax({
			url: tagManagerServiceUrl + "/ReorderTagHierarchyPositions",
			data: '{ "orderedTagKeys" : "' + orderedNodes.join(',') + '", "tagTreeId" : "' + $('#tagTreeId').text() + '" }',
			dataType: 'json',
			type: 'POST',
			contentType: "application/json; charset=utf-8",
			processdata: true
		});
	}

	function openFormDialog(url) {
		var options = {
			url: url,
			dialogReturnValueCallback: callback_openFormDialog
		};
		SP.UI.ModalDialog.showModalDialog(options);

		function callback_openFormDialog(dialogResult, returnValue) {
			location.reload(true);
		}
	}
});